var rootPath = null;
var targetUrl = null;
var processMoniter = null;
var initCallbackAction = null;
var resourceFileWriter = null;
var remoteFileEntry = null;
var needUpdate = false;
var downloadTry = 0;
var MAIN_fileSystem = null;

/*
 * 初始化，然后转向目标网页
 */
function initProcess(url,firstRun,sdkver) {
	console.log("init the file system,first run:" + firstRun + " and sdkver:" + sdkver);
	var fail = function(error) {
		console.log("file oper fail:" + error.code);
	};
	var fileSystemFetch = function(fileSystem){
		//把文件系统对象赋给全局变量
        if (device.platform.toLowerCase() === "android") {
            MAIN_fileSystem = fileSystem;
        } else {
            MAIN_fileSystem = fileSystem.root;
        }
		console.debug("MAIN_fileSystem is:" + JSON.stringify(MAIN_fileSystem));
		GLOABAL_SYSTEMROOT_ABS = MAIN_fileSystem.toURL();
		console.log("GLOABAL_SYSTEMROOT_ABS is:" + GLOABAL_SYSTEMROOT_ABS + " and GLOBALVAR_storeAppResource:" + GLOBALVAR_storeAppResource);
		targetUrl = GLOABAL_SYSTEMROOT_ABS + GLOBALVAR_storeAppResource + "/" + url;
		console.log("targetUrl issss:" + targetUrl);
		//初始化目录
		directoryInit(function(){
			//如果安装后第一次使用，则需要拷贝程序，否则进行版本比较
			if(firstRun==1){
				firstProcess();
			}else{
				console.log("no need first");
				resourceFileProcess();
			}
		},sdkver);
	};
	var fileTransfer = new FileTransfer();
	console.log("window.sessionStorage:",window.sessionStorage);
	if (device.platform.toLowerCase() === "android") {
        window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, fileSystemFetch, fail);
    } else {
        // for iOS
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemFetch, fail);
    }
}
//初始化目录
function directoryInit(callbackAction,sdkver){
	var printDirPath = function(entry) {
		console.log("Dir path - " + entry.fullPath);
	};
	var process = function(){
	                 //创建私聊音频文件目录
                            createDirectory(GLOBALVAR_storeChatAudioFilePath, printDirPath);
                            //创建话题配音文件目录
                            createDirectory(GLOBALVAR_storeTopicAudioFilePath, printDirPath);
                            //创建资源文件目录
                            createDirectory(GLOBALVAR_storeResource, printDirPath);
                            //创建临时文件目录
                            createDirectory(GLOBALVAR_storeTempResFilePath, printDirPath);
                            //创建应用文件目录
                            createDirectory(GLOBALVAR_storeAppResource, function(directoryEntry) {
                                console.log("GLOBALVAR_storeAppResource directory in:" + directoryEntry.fullPath);
                                if(callbackAction){
                                    callbackAction();
                                }
                            });
	};
	//6.0以前还是原来的方式
	if(sdkver<23){
	    process();
	}else{
	    //6.0以上版本需要申请运行时权限
       cordova.plugins.diagnostic.requestExternalStorageAuthorization(function(status){
            console.log("Authorization request for external storage use was " + (status == cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
            if(status == cordova.plugins.diagnostic.permissionStatus.GRANTED){
                    console.log("Permission granted to use the WRITE_EXTERNAL_STORAGE");
                    process();
            }else{
                alert("授权失败，退出");
                navigator.app.exitApp();
            }
        }, function(error){
            console.error("The following error occurred: ",error);
            alert("未知错误，退出")
            navigator.app.exitApp();
        });
	}


}
//第一次使用的流程
function firstProcess(){
    //清除之前的本地缓存
    localStorage.clear();
    console.log("localStorage clear");
	//第一次直接下载云端资源包
    resourceFileProcess();
    return;
}
/*
 * 处理本地文件更新
 */
function resourceFileProcess(){
	var fileName = GLOBALVAR_storeAppResource + "/resource.json";
	console.log("fileName is:" + fileName);
	var url = GLOBALVAR_resourceUrl + "/resource.json?ver=" + Math.random();
	var retryCnt = 0;
	//下载版本文件，并比较更新
	downloadVersionFile(url,function(remoteResource){
		//如果没有获得信息，则返回
		if(!remoteResource){
			endProcess();
			return;
		}
		var localResource = null;
		//读取本地资源版本文件
		var reader = new FileReader();
		var fileOperator = $.extend({},FileOperator,{noCamera:true});
		//获得本地版本文件
		fileOperator.isFileExists(fileName, function(fileEntry) {
			fileEntry.file(function(file){
			    reader.onloadend = function(evt) {
			        console.log("reads success,result:" + evt.target.result);
			        localResource = JSON.parse(evt.target.result);
			        console.log("localResource build:" + localResource.version);
			        compareResourceFile(localResource,remoteResource);
			    };
			    reader.onerror = function(error){
			    	console.log("read err:" + error.code);
			    };
			    reader.readAsText(file);
			}, function(){
				console.log("fail getFile:" + fileName);
			});
		}, function() {
			console.log("err for file not exists:" + fileName);
			//如果没有，直接下载
			wholeDownload();
		});
	});
}
function downloadVersionFile(url,callbackAction){
	var jsonFile = GLOBALVAR_storeAppResource + "/resource_remote.json?ver=" + Math.random();
	console.log("jsonFile is:" + jsonFile);
	var fileOperator = $.extend({},FileOperator,{noCamera:true});
	fileOperator.downloadFile(url, jsonFile, function(fileEntry) {
	        console.log("download complete: " + fileEntry.fullPath);
	        downloadTry = 0;
	        //记录此文件entry，用于后续复制
	        remoteFileEntry = fileEntry;
	        //下载后读取文件内容
			fileEntry.file(function(file){
				var reader = new FileReader();
			    reader.onloadend = function(evt) {
			        console.log("reads remote file success,result:" + evt.target.result);
			        var remoteResource = JSON.parse(evt.target.result);
			        console.log("remoteResource version:" + remoteResource.version);
			        callbackAction(remoteResource);
			    };
			    reader.onerror = function(error){
			    	console.log("read remote file err:" + error.code);
			    	callbackAction();
			    };
			    reader.readAsText(file);
			});
	}, function(error) {
	        console.log("download error source: " + error.source);
	        console.log("download error target: " + error.target);
	        console.log("download error code:" + error.code);
	        callbackAction();
	});
}
//进行比较
function compareResourceFile(localResource,remoteResource){
	console.log("remoteResource.version:" + remoteResource.version + " and localResource.version:" + localResource.version);
	//版本没有更新，不用下载
	if(remoteResource.version<=localResource.version){
		console.log("no need update ver");
		needUpdate = false;
		console.log("go href 3:" + targetUrl);
		window.location.href = targetUrl;
		return;
	}
	needUpdate = true;
	//如果当前版本小于强制更新版本，则整包更新
	if(localResource.version<remoteResource.forceUpdateVersion){
		wholeDownload();
		return;
	}
	//设置监视器，用于异步检查完成情况
	processMoniter = {end:false,completeCnt:0,totalCnt:5};
	var downloadList = new Array();
	var index = 0;
	//最多取前5个比较
	for(var i=0;i<5;i++){
		var entry = remoteResource.resource[i];
		var remoteUrl = GLOBALVAR_resourceUrl + "/" + entry.path + "/" + entry.file;
		var filePath = GLOBALVAR_storeAppResource + "/" + entry.path + "/" + entry.file;
		var downloadItem = {
			remoteUrl : remoteUrl,
			filePath : filePath
		};
		//放入数组，后续一并下载
		downloadList.push(downloadItem);
		console.log("need update,remoteUrl:" + remoteUrl + " and filePath:" + filePath);
	}
	batchDownload(downloadList);
}

function batchDownload(downloadList){
	//如果下载文件过多，则直接下载资源包
	if(downloadList.length>20){
		wholeDownload();
		return;
	}
	for(var i=0;i<downloadList.length;i++){
		var downloadItem = downloadList[i];
		var fileOperator = $.extend({},FileOperator,{noCamera:true});
		fileOperator.downloadFile(downloadItem.remoteUrl, downloadItem.filePath, function(entry) {
			console.log("download suc,file:" + entry.fullPath);
			endJudge();
		}, function() {
			console.log("download err,url:" + downloadItem.remoteUrl);
			endJudge();
		});

	}
}

function wholeDownload(){
	console.log("need download zip");
	var remoteUrl = GLOBALVAR_resourceUrl + "/resource.zip";
	var zipFile = GLOBALVAR_storeAppResource + "/resource.zip";
	var fileOperator = $.extend({},FileOperator,{noCamera:true});
	fileOperator.downloadFile(remoteUrl, zipFile, function() {
		console.log("download zip suc,file:" + zipFile);
		//解压资源包
		var sysFuncPlugin = cordova.require('org.apache.cordova.plugin.SysFuncPlugin');
		sysFuncPlugin.unzipFile({
			path : GLOBALVAR_storeAppResource,
			zipname : "resource.zip"
		}, function(status) {
			console.log("extract zip suc,status:" + status);
			endProcess(true);
		}, function(error) {
			console.log("extract zip err,file:" + error);
		});
	}, function(error) {
		console.log("download zip err,file:" + zipFile);
		endProcess();
	});

}
function endJudge(){
	var complete = true;
	processMoniter.completeCnt = processMoniter.completeCnt + 1;
	console.log("processMoniter now:" + JSON.stringify(processMoniter));
	if(processMoniter.completeCnt==processMoniter.totalCnt){
		//需要更新版本文件
		endProcess(true);
	}
}

function endProcess(updateVersionFile){
	//更新版本文件
	if (updateVersionFile) {
		MAIN_fileSystem.getDirectory(GLOBALVAR_storeAppResource, {
			create : false,
			exclusive : true
		}, function(resourceDirEntry) {
			console.log("resourceDirEntry is:" + resourceDirEntry.fullPath);
			remoteFileEntry.copyTo(resourceDirEntry,"resource.json",function(entry){
				console.log("copy suc,entry:" + entry.fullPath);
				console.log("go href:" + targetUrl);
				window.location.href = targetUrl;
			},function(error){
				console.log("copy error:" + error.code);
			});
		}, function(evt) {
			console.log("resourceDirEntry not exists:" + evt.code);
		});
	}else{
		console.log("go href 2:" + targetUrl);
		window.location.href = targetUrl;
	}
}

function createDirectory(path, success){
    var dirs = path.split("/").reverse();
    var root = MAIN_fileSystem;
    var createDir = function(dir){
        console.log("create dir " + dir);
        root.getDirectory(dir, {
            create : true,
            exclusive : false
        }, successCB, failCB);
    };
    var successCB = function(entry){
        console.log("dir created " + entry.fullPath);
        root = entry;
        if(dirs.length > 0){
            createDir(dirs.pop());
        }else{
            console.log("all dir created");
            success(entry);
        }
    };

    var failCB = function(){
        console.log("failed to create dir " + dir);
    };

    createDir(dirs.pop());
}

function readFileFromAssetWww(filePath,callback){
    var request = new XMLHttpRequest();
    request.open("GET", filePath);
    request.withCredentials = "true";
    request.onreadystatechange = function() {
            if (request.status==404) {
               console.log("fail get file with path:" + filePath);
            }
            if (request.readyState == 4) {
                var xml = request.responseXML;
                console.log("get xml:" + xml);
                callback(xml);
        	}
    };
    request.send();
}
